import path from "path";
import fsPromises from "fs/promises";
import sqlite from "src/config/sqlite";

let db: Database | null = null;

function initSql() {
  const projectPath = path.resolve(__dirname, "../assets/project_info.sql");
  const snapshotPath = path.resolve(__dirname, "../assets/snapshot_info.sql");
  Promise.all([
    fsPromises.readFile(projectPath, "utf8"),
    fsPromises.readFile(snapshotPath, "utf8"),
  ]).then(([project_sql, snapshot_sql]) => {
    db!.exec(project_sql);
    db!.exec(snapshot_sql);
  });
}

function initDatabase() {
  db = sqlite((isInit: boolean) => {
    if (!isInit) initSql();
  });
}

export { db };

export default initDatabase;
